<?php

namespace Wanecho\Mobilelogin\Api\Controllers;

use Flarum\Settings\SettingsRepositoryInterface;
use Psr\Http\Message\ServerRequestInterface;
use Wanecho\Mobilelogin\Api\Libraries\SMS;
use Illuminate\Support\Arr;
use Laminas\Diactoros\Response\JsonResponse;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Wanecho\Mobilelogin\Api\WanechoSms;
use Carbon\Carbon;
use Flarum\Foundation\ValidationException;
use Wanecho\Mobilelogin\Api\Validators\MobileValidator;
use Illuminate\Contracts\Cache\Repository;

class RegSendcodeController implements RequestHandlerInterface
{
    // public $serializer = SendCodeSerializer::class;
    protected $settings;
    protected $validator;
    protected $cache;

    public function __construct(
        SettingsRepositoryInterface $settings,
        MobileValidator $validator,
        Repository $cache
    ) {
        $this->settings = $settings;
        $this->validator = $validator;
        $this->cache = $cache;
    }

    public function handle(ServerRequestInterface $request): ResponseInterface
    {
        $body = $request->getParsedBody();
        $mobile = Arr::get($body, 'mobile');
        $captcha = Arr::get($body, 'captcha');

        $this->validator->assertValid([
            'mobile' => $mobile,
            'captcha' => $captcha,
        ]);
        //检测验证码是否正确
        $session =  $request->getAttribute('session');
        $captcha_local =  $this->cache->get('captcha' . $session->getId());
        if ($captcha != $captcha_local) {
            throw new ValidationException([
                'msgcode' => '图形验证码错误',
            ]);
        }
        //验证码失效
        $this->cache->forget('captcha' . $session->getId());

        $code = random_int(100000, 999999);
        $SMS = new SMS($this->settings);
        try {
            // $res = true;
            $res = $SMS->sendSMS(
                $mobile,
                $this->settings->get('mobilelogin.TemplateCode'),
                $params = [
                    'code' => $code
                ],
                $this->settings->get('mobilelogin.SignName')
            );
        } catch (\Throwable $th) {
            return new JsonResponse($th->getMessage(), 500);
        }

        if ($res === false) {
            return new JsonResponse('验证码发送失败', 500);
        }
        $created_at = Carbon::now();
        // 记录到表，后续用于校验
        WanechoSms::create([
            'mobile' => $mobile,
            'code' => $code,
            'is_active' => 0,
            'created_at' => $created_at
        ]);
        // throw new Exception('Invalid state');
        return new JsonResponse('验证码已发送', 200);
    }
}
